<template>
	<div>
		<div class="header">
			{{testDetail.title}}
		</div>
		<div class="info">
			<div class="avatar">
				<span>头像</span>
				<img :src="testDetail.avatorUrl" class="user-avatar">
			</div>
			<div class="name h100">
				<span>姓名</span>
				{{testDetail.displayName}}
			</div>
			<div class="num h100">
				<span>学号</span>{{testDetail.userNo}}
			</div>
			<div class="test-time">
				<span>考试时间</span>
				<span class="period">{{testDetail.startTime}}~ {{testDetail.endTime}}</span>
			</div>
			<div class="advance-login-time h100">
				<span>提前登录时长</span>{{testDetail.advanceTime}}分钟
			</div>
			<div class="delay-time h100">
				<span>延迟登录时长</span>{{testDetail.extendTime}}分钟
			</div>
			<div class="advance-hand-time h100">
				<span>提前交卷时长</span>{{testDetail.allowTime}}分钟
			</div>
			<div class="test-requirement h100">
				<span>考试要求</span>
				<div v-if="remarkShow"></div>
				<div v-else>暂无要求</div>
			</div>
			<div class="photo-count" v-if="photo_count>0&&photo_timer">
				拍照倒计时 {{photo_count}}s
			</div>
		</div>

		<!-- <view class="confirm">
			<view class="is-check" @click="checked=!checked">
				<checkbox :checked="checked" />我已阅读并同意
			</view>
			<view class="enter " :class="refresh?'refresh':''" @click="enterTest">
				关闭进入考试 <text v-if="count>0">({{count}}s)</text>
			</view>
		</view> -->

		<!-- <uni-popup ref="popup" background-color="#fff" :is-mask-click="false">
			<view class="popup-content">
				<view class="pop-header">
					提示 <image src="@/static/testvalid/icon-close.png" class="close" @click="hide"></image>
				</view>
				<view class="pop-body">
					请先勾选同意
				</view>
				<view class="pop-footer">
					<text @click="hide">
						确认
					</text>
				</view>
			</view>
		</uni-popup> -->

		<!-- <uni-popup ref="modal" background-color="#fff" :is-mask-click="false">
			<view class="modal-body">
				<view class="modal-content">
					{{content}}
				</view>
				<view class="modal-footer" @click="confirmEnter">
					确认
				</view>
			</view>
		</uni-popup> -->

		<van-dialog v-model="showDialog" @confirm="confirmEnter">
			{{content}}
		</van-dialog>

		<div class="oe-exam-camera" style="height: 240px;" v-show="isUseCamera && photo_count > 0">
			<video id="video" width="280" height="240" preload autoplay loop muted></video>
			<canvas id="canvas" width="280" height="240"></canvas>
			<canvas id="canvas2" width="320" height="240" style="display:none;"></canvas>
		</div>

	</div>

</template>

<script>
import "@/lib/faceTrack/tracking-min.js";
import "@/lib/faceTrack/face-min.js";

export default {
	name: "test-valid",
	data() {
		return {
			checked: false,
			refresh: false,
			count: 5,
			photo_count: 5,
			timer: null,
			photo_timer: null,
			testDetail: {},
			showModal: false,
			content:
				"该考试进入前需要拍照记录，请保证本人正面在摄像范围内。点击确认后5s拍照。",
			remarkShow: false,
			cameraChangeCount: 0,
			cameraBuckleScore: "",
			trackerTask: '',
			workExamStuId: "",
			isUseCamera: false,
			mediaStreamTrack: "",
			isStart: false,
			showDialog: false,

			collapsed: false,
      browser: '',
      startTime: '',
      endTime: '',
      advanceTime: 0,
      extendTime: 0,
      allowTime: 0,
      changePaperCount: '',
      buckleScore: '',
      remark: '',
      remarkIs: false,
      monitorMobile: '',
      wait: 5,
      enterShow: true,
      loading: false,
      canEnterDoTime: 10000,
      takeTime: 5,
      agree: false
		};
	},
	mounted() {
		const examId = this.$route.params.id;
		this.getPoint(examId);
	},
	destroyed() {
		clearInterval(this.canEnterTimeInterval);
		if (this.isUseCamera && this.isStart) {
			this.trackerTask.stop();
		}
		// 关闭摄像头
		if (this.isUseCamera && this.isStart) {
			this.mediaStreamTrack.srcObject &&
				this.mediaStreamTrack.srcObject.getTracks()[0].stop();
			// this.trackerTask.closeCamera();
			// window.tracking.closeCamera();
			// console.log('执行了关闭');
		}
	},
	methods: {
		getPoint(id) {
			this.$toast.loading({
				message: "加载中...",
				forbidClick: true,
				duration: 0,
			});
			window.console.log(id);
			const browser = localStorage.getItem("browser");
			const sourceType = localStorage.getItem("sourceType");
			this.$api.test
				.testInfo({
					examId: id,
					browser: browser,
					sourceType: sourceType,
				})
				.then((res) => {
					if (res.code > 0) {
						this.testDetail = res;
						this.changePaperCount = res.changePaperCount; //切屏次数
						this.buckleScore = res.buckleScore; //切屏每次扣分
						this.cameraChangeCount = res.cameraChangeCount;
						this.cameraBuckleScore = res.cameraBuckleScore;
						this.workExamStuId = res.workExamStuId; // 学生作答ID
						this.isUseCamera = res.isUseCamera; //是否开始摄像
						if (res.remark) {
							this.remarkShow = true;
						} else {
							// 是否监测摄像
							if (res.isUseCamera) {
								// this.openCamera();
								this.setTake();
							} else {
								this.isStart = true;
								// this.getSecond();
							}
						}
					} else {
						// 提示 ，返回上一页
						this.$msg.confirm(res.msg, false, "red").then(() => {
							this.$router.back();
						});
					}
				})
				.finally(() => {
					this.$toast.clear();
				});
			// study/workexam/getPointInfo
			// const browser = localStorage.getItem('browser')
			// const sourceType = localStorage.getItem('sourceType')
			// this.$http.post(`${enterTest}`, {
			// 	examId: id,
			// 	browser: browser,
			// 	sourceType: sourceType
			// }).then(res => {
			// 	window.console.log(res);
			// 	if (res.code > 0) {
			// 		this.testDetail = res
			// 		this.changePaperCount = res.changePaperCount; //切屏次数
			// 		this.buckleScore = res.buckleScore; //切屏每次扣分
			// 		this.cameraChangeCount = res.cameraChangeCount;
			// 		this.cameraBuckleScore = res.cameraBuckleScore;
			// 		this.workExamStuId = res.workExamStuId; // 学生作答ID
			// 		this.isUseCamera = res.isUseCamera; //是否开始摄像
			// 		if (res.remark) {
			// 			this.remarkShow = true;
			// 		} else {
			// 			// 是否监测摄像
			// 			if (res.isUseCamera) {
			// 				this.openCamera();
			// 				this.setTake();
			// 			} else {
			// 				this.isStart = true;
			// 				// this.getSecond();
			// 			}
			// 		}

			// 		// this.canEnterDoTime = res.canEnterDoTime;
			// 		// if (this.canEnterDoTime > 0) {
			// 		// 	this.canEnterTimeInterval = setInterval(() => {
			// 		// 		this.canEnterDoTime--;
			// 		// 	}, 1000);
			// 		// }

			// 		// this.$emit('enterExam')
			// 		// uni.setStorageSync('testDetail', res)

			// 	} else {
			// 		// 提示 ，返回上一页
			// 		// uni.navigateBack({
			// 		// 	delta: 0
			// 		// })
			// 	}

			// })
		},
		confirmEnter() {
			this.takePhotoCount();
		},
		// 监测摄像
		// 考试录像
		openCamera() {
			var video = (this.mediaStreamTrack = document.getElementById("video"));
			var canvas = document.getElementById("canvas");
			var canvas2 = document.getElementById("canvas2");
			var context = canvas.getContext("2d");
			var tracker = new window.tracking.ObjectTracker("face");
			tracker.setInitialScale(4);
			tracker.setStepSize(2);
			tracker.setEdgesDensity(0.1);

			this.trackerTask = window.tracking.track("#video", tracker, {
				camera: true,
			});
			// var isFirstStart = true;
			var that = this;
			tracker.on("track", function (event) {
				window.console.log(event);
				if (!that.isStart) {
					that.isStart = true;
				}
				context.clearRect(0, 0, canvas.width, canvas.height);
			});
		},
		getTake() {
			var that = this;
			setTimeout(() => {
				if (that.takeTime) {
					that.takeTime--;
					that.getTake();
				} else {
					that.snap();
					that.mediaStreamTrack.srcObject.getTracks()[0].stop();
					that.$msg.success("已拍照");
				}
			}, 1000);
		},
		setTake() {
			const h = this.$createElement;
			var that = this;
			this.$msg
				.confirm(this.content, true, "", "温馨提示")
				.then(() => {
					that.getTake();
				})
				.catch(() => {
					this.$router.back();
				});
		},
		snap() {
			var video = (this.mediaStreamTrack = document.getElementById("video"));
			var canvas2 = document.getElementById("canvas2");
			// //绘制canvas图形
			canvas2.getContext("2d").drawImage(video, 0, 0, 320, 240);
			// //把canvas图像转为img图片
			// // img.src = canvas2.toDataURL("image/png");
			// //执行上传
			this.saveExamPic(canvas2);
		},
		saveExamPic(canvas2) {
			let completeUrl = canvas2.toDataURL("image/png");
			let urlArr = completeUrl.split(",");
			let base64 = urlArr[1];
			let imgType = urlArr[0].replace("data:image/", "").replace(";base64", "");
			let file_system_url = localStorage.getItem("file_system_url");
			let postUrl = `${file_system_url}&extension=${imgType}&encode=base64`;
			this.$http.post(postUrl, base64).then((data) => {
				if (data) {
					this.randomSaveCameraPage(data.url);
					this.getSecond();
				}
			});
		},
		randomSaveCameraPage(url) {
			var browser = this.getBrowser();
			this.$http
				.post("/api/study/workexam/randomSaveCameraPage", {
					workExamStuId: this.workExamStuId, //学生作答Id
					workExamId: this.Id, //考试Id
					browser: browser, //浏览器类型
					url: url,
				})
				.then((res) => {
					if (res.code != 1) {
						this.$message.error(res.msg);
					}
				});
		},
		// openCamera() {
		// 	console.log('打开摄像头');
		// 	this.$refs.modal.open('center')
		// 	// var _this = this
		// 	// uni.chooseImage({
		// 	// 	count: 1, //默认9
		// 	// 	sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
		// 	// 	sourceType: ['camera'], //从相册选择、摄像头
		// 	// 	success: function(res) {
		// 	// 		// _this.imgShow = res.tempFilePaths[0]
		// 	// 		console.log(res);
		// 	// 	}
		// 	// });

		// 	// 倒计时5s拍照 后 ，倒计时开始准备进入考试

		// },
		enterTest() {
			if (this.timer) {
				return false;
			} else {
				if (!this.checked) {
					this.$refs.popup.open("center");
				} else {
					// uni.reLaunch({
					// 	url: '/pages/exam/exam'
					// })
				}
			}
		},
		takePhotoCount() {
			this.$refs.modal.close();
			const TIME_COUNT = 5;
			if (!this.photo_timer) {
				this.photo_count = TIME_COUNT;
				this.photo_timer = setInterval(() => {
					if (this.photo_count > 0 && this.photo_count <= TIME_COUNT) {
						this.photo_count--;
					} else {
						// 拍照，上传 ,成功提示
						this.$refs.uToast.show({
							title: "拍照成功",
							type: "default",
						});
						clearInterval(this.photo_timer);
						this.photo_timer = null;
						this.countDown();

						this.snap();
						this.mediaStreamTrack.srcObject.getTracks()[0].stop();
					}
				}, 1000);
			}
		},
		countDown() {
			this.refresh = true;
			const TIME_COUNT = 5;
			if (!this.timer) {
				this.count = TIME_COUNT;
				this.timer = setInterval(() => {
					if (this.count > 0 && this.count <= TIME_COUNT) {
						this.count--;
					} else {
						clearInterval(this.timer);
						this.timer = null;
					}

					if (this.count == 0) {
						this.refresh = false;
					}
				}, 1000);
			}
		},
		hide() {
			this.$refs.popup.close();
		},
	},
};
</script>

<style lang="less" scoped>
@import "index.less";
</style>
